package com.brillilab.starter.task;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.brillilab.common.alioss.OssFileEnum;
import com.brillilab.common.alioss.OssUtils;
import com.brillilab.domain.enums.common.BoolEnum;
import com.brillilab.domain.po.experiments.Experiment;
import com.brillilab.domain.po.lab.LabMember;
import com.brillilab.domain.po.system.FileDownload;
import com.brillilab.domain.po.system.FileManage;
import com.brillilab.domain.po.system.SystemConfig;
import com.brillilab.domain.po.topics.Topic;
import com.brillilab.domain.po.topics.TopicMember;
import com.brillilab.domain.vo.team.TeamMemberVo;
import com.brillilab.service.core.experiments.IExperimentService;
import com.brillilab.service.core.lab.ILabMemberService;
import com.brillilab.service.core.system.IFileDownloadService;
import com.brillilab.service.core.system.IFileManageService;
import com.brillilab.service.core.system.ISystemConfigService;
import com.brillilab.service.core.topics.ITopicMemberService;
import com.brillilab.service.core.topics.ITopicService;
import com.brillilab.service.logic.team.TeamLogic;
import com.brillilab.service.module.message.producer.MessageProducer;
import com.brillilab.service.module.message.template.impl.files.FileExpireRemindTemp;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;

/**
 * 文件下载任务
 * 
 * @author LJ
 *
 */
@Component
public class FileDownloadTask {
	@Resource
	private ISystemConfigService systemConfigService;
	@Resource
	private IFileManageService fileManageService;
	@Resource
	private IFileDownloadService fileDownloadService;
	@Resource
	private ITopicMemberService topicMemberService;
	@Resource
	private ITopicService topicService;
	@Resource
	private IExperimentService experimentService;
	@Resource
	private ILabMemberService labMemberService;
	@Resource
	private TeamLogic teamLogic;
	@Resource
	private OssUtils ossUtil;
	@Resource
	private MessageProducer messageProducer;

	private Map<Long, List<Long>> topicMemberMap = CollUtil.newHashMap();
	private Map<Long, Long> experimentTopicMap = CollUtil.newHashMap();

	/**
	 * 启动文件过期定时任务（每日凌晨3点执行一次）0 0 3 * * ? 
	 */
	@Scheduled(cron = "0 0 3 * * ?")
	public void startTask() {
		int expireDay = getFileExpireDate();
		List<Integer> fileEnums = CollUtil.newArrayList(OssFileEnum.AnalyzeDataFile.getKey(),
				OssFileEnum.AnalyzeDataFileThumbnail.getKey(), OssFileEnum.PrimaryDataFile.getKey());
		List<FileManage> fileList = fileManageService.selectList(fileEnums);
		if (CollUtil.isNotEmpty(fileList)) {
			List<FileManage> expireFiles = CollUtil.newArrayList();
			Map<Long, Long> sendSmgMap = CollUtil.newHashMap();

			for (FileManage file : fileList) {
				long betweenDay = DateUtil.betweenDay(file.getCreateTime(), new Date(), false);
				long surplusDay = expireDay - betweenDay;
				if (surplusDay <= 0) {
					expireFiles.add(file);
				} else if (surplusDay == 7 || surplusDay == 1) {
					List<Long> labMemberIds = getLabMemberIds(file.getReferDataId());
					if(CollUtil.isNotEmpty(labMemberIds)) {
						labMemberIds.forEach(labMemberId ->{
							FileDownload download = fileDownloadService.getFileDownload(file.getId(), labMemberId);
							if(download==null || (download.getApp()==0 && download.getPc()==0)) {
								sendSmgMap.put(labMemberId, surplusDay);
							}
						});
					}
				}
			}
			this.deleteFile(expireFiles);
			this.sendMsg(sendSmgMap);
		}
	}

	/**
	 * 发送消息
	 * 
	 * @param file
	 * @param differ
	 */
	private void sendMsg(Map<Long, Long> sendSmgMap) {
		if(CollUtil.isNotEmpty(sendSmgMap)) {
			List<Long> labMemberIds = CollUtil.newArrayList(sendSmgMap.keySet());
			List<LabMember> memberList = labMemberService.selectListByIds(labMemberIds);
			memberList.forEach(member -> {
				Long surplusDay = sendSmgMap.get(member.getId());
				FileExpireRemindTemp temp = new FileExpireRemindTemp(member.getLabId(), member.getUserId(), member.getId(),
						String.valueOf(surplusDay));
				messageProducer.sendMessagePush(temp);
			});
		}
	}

	/**
	 * 删除附件
	 * 
	 * @param expireFiles
	 */
	private void deleteFile(List<FileManage> expireFiles) {
		if (CollUtil.isNotEmpty(expireFiles)) {
			List<Long> expireIds = expireFiles.stream().map(FileManage::getId).collect(Collectors.toList());
			fileManageService.updateIsDownload(expireIds);
//			OSSClient ossClient = ossUtil.initClient();
//			for (FileManage file : expireFiles) {
//				OssUtils.deleteFile(ossClient, file.getBucketName(), file.getPath());
//			}
		}
	}

	/**
	 * 判断有权限的是否都下载完成
	 * 
	 * @param expireIds
	 * @param file
	 * @return
	 */
	private boolean isAllDownload(Long fileId, Long referDataId) {
		List<FileDownload> downloadList = fileDownloadService.getFileDownloadList(fileId);
		if (CollUtil.isNotEmpty(downloadList)) {
			List<Long> downloadMemberIds = downloadList.stream().map(FileDownload::getLabMemberId)
					.collect(Collectors.toList());
			List<Long> labMemberIds = this.getLabMemberIds(referDataId);
			if (CollUtil.isEmpty(labMemberIds)) {
				return true;
			} else if (CollUtil.containsAll(downloadMemberIds, labMemberIds)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取有权限查看的成员ID
	 * 
	 * @return
	 */
	private List<Long> getLabMemberIds(Long experimentId) {
		List<Long> labMemberIds = CollUtil.newArrayList();
		Long topicId = experimentTopicMap.get(experimentId);
		if (topicId == null) {
			Experiment experiment = experimentService.selectById(experimentId);
			if (experiment != null)
				topicId = experiment.getTopicId();
		}
		if (topicId != null) {
			List<Long> memberIds = topicMemberMap.get(topicId);
			if (CollUtil.isNotEmpty(memberIds)) {
				return memberIds;
			}

			Topic topic = topicService.selectById(topicId);
			if (topic != null && topic.getIsDelete().equals(BoolEnum.FALSE.getValue())) {
				List<TopicMember> list = topicMemberService.selectListByTopicId(topicId);
				if (CollUtil.isNotEmpty(list)) {
					List<Long> ids = list.stream().map(TopicMember::getLabMemberId).collect(Collectors.toList());
					labMemberIds.addAll(ids);
				}
				LabMember owner = labMemberService.getOwner(topic.getLabId());
				if (owner != null)
					labMemberIds.add(owner.getId());
				TeamMemberVo leader = teamLogic.getLeaderOfTeamMember(topic.getLabId(), topic.getExecutorId());
				if (leader != null)
					labMemberIds.add(leader.getLabMemberId());
			}
			if(CollUtil.isNotEmpty(labMemberIds)) {
				labMemberIds = CollUtil.distinct(labMemberIds);
				topicMemberMap.put(topicId, labMemberIds);
			}
		}
		return labMemberIds;

	}

	/**
	 * 获取过期日期
	 * 
	 * @return
	 */
	private int getFileExpireDate() {
		int date = 30;
		SystemConfig config = systemConfigService.selectByCode("file_expire");
		if (config != null) {
			JSONObject jsonObject = JSON.parseObject(config.getValue());
			if (jsonObject != null && jsonObject.get("date") != null)
				date = Integer.valueOf(jsonObject.get("date").toString());
		}
		return date;
	}

}
